#!/bin/bash
set -e

CACHE_MAX_SIZE=${CACHE_MAX_SIZE:-100}
CACHE_MAX_OBJECT_SIZE=${CACHE_MAX_OBJECT_SIZE:-400}
CACHE_MAX_MEM=${CACHE_MAX_MEM:-256}

OVERALL_SPEED_KBPS=${OVERALL_SPEED_KBPS:--1}
if [ ${OVERALL_SPEED_KBPS} -gt 0 ]; then
  OVERALL_SPEED_KBPS=$((${OVERALL_SPEED_KBPS} * 1000  / 8))
fi

INDIVIDUAL_SPEED_KBPS=${INDIVIDUAL_SPEED_KBPS:--1}
if [ ${INDIVIDUAL_SPEED_KBPS} -gt 0 ]; then
  INDIVIDUAL_SPEED_KBPS=$((${INDIVIDUAL_SPEED_KBPS} * 1000  / 8))
fi

SQUID_HOME=/usr/local/squid
SQUID_CONF=$SQUID_HOME/etc/squid.conf

# apply squid config
sed 's/{{CACHE_MAX_SIZE}}/'"${CACHE_MAX_SIZE}"'/' -i $SQUID_CONF
sed 's/{{CACHE_MAX_OBJECT_SIZE}}/'"${CACHE_MAX_OBJECT_SIZE}"'/' -i $SQUID_CONF
sed 's/{{CACHE_MAX_MEM}}/'"${CACHE_MAX_MEM}"'/' -i $SQUID_CONF

sed 's/{{INDIVIDUAL_SPEED_KBPS}}/'"${INDIVIDUAL_SPEED_KBPS}"'/g' -i $SQUID_CONF
sed 's/{{OVERALL_SPEED_KBPS}}/'"${OVERALL_SPEED_KBPS}"'/g' -i $SQUID_CONF

if [ -e $SQUID_HOME/var/run/squid/squid.pid ]; then
  rm -f $SQUID_HOME/var/run/squid/squid.pid
fi

# initialize the cache_dir
if [ ! -d $SQUID_HOME/var/cache/squid/00 ]; then
  $SQUID_HOME/sbin/squid -N -z
fi

exec $SQUID_HOME/sbin/squid -NYC -d 1
